package groups

import (
	"encoding/json"
	"strconv"
	"xpms/controllers"
	"xpms/cores/utils"
)

//  组成员管理
type ManageGroupPermissionController struct {
	controllers.BaseController
}

// @Title Get
// @Description get GroupPermission by id
// @Param	id		path 	string	true		"The key for GroupPermission"
// @Success 200 {object} groups.GroupsPermission
// @Failure 403 :id is empty
// @router /:id [get]
func (u *ManageGroupPermissionController) GetPermissionByGroupId() {
	uid := u.GetString(":id")
	if uid != "" {
		int64, _ := strconv.ParseInt(uid, 10, 64)
		groupspermissions := ListGroupsPermission(int64)
		u.Data["json"] = groupspermissions
	}
	u.ServeJSON()
}

type AddGroupPermission struct {
	GroupId     string
	Permissions []string
}

// @Title 添加组权限
// @Description 添加组权限
// @Param	body		body 	groups.AddGroupPermission	true		"body for groupPermission content"
// @Success 200 {string} groups.Groups.Id
// @Failure 403 body is empty
// @router / [post]
func (u *ManageGroupPermissionController) AddGroupPermission() {
	var group AddGroupPermission
	json.Unmarshal(u.Ctx.Input.RequestBody, &group)
	if utils.IsEmpty(group.GroupId) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "请选择组"}
		u.ServeJSON()
		return
	} else if utils.IsEmpty(group.Permissions) {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "请选择需要分配的权限"}
		u.ServeJSON()
		return
	}
	var upd []GroupsPermission
	int64, _ := strconv.ParseInt(group.GroupId, 10, 64)
	for _, v := range group.Permissions {
		//id := utils.SnowFlakeId()
		utils.UUID.Init(1024)
		id, _ := utils.UUID.GetId()
		permission := new(GroupsPermission)
		permission.Id = id
		permission.Groupid = int64
		vint64, _ := strconv.ParseInt(v, 10, 64)
		permission.Permissionid = vint64
		upd = append(upd, *permission)
	}
	err := AddGroupsPermissions(group.GroupId, upd)
	if err == nil {
		u.Data["json"] = map[string]interface{}{"code": 1, "message": "操作成功", "id": group.GroupId}
	} else {
		u.Data["json"] = map[string]interface{}{"code": 0, "message": "添加失败"}
	}
	u.ServeJSON()
}
